
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:usb_serial/usb_serial.dart';

class SerialPage extends StatefulWidget {
  UsbDevice usbdevices;
  SerialPage({Key? key,required this.usbdevices}) : super(key: key);
  @override
  State<SerialPage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<SerialPage>{
  var textController=TextEditingController();
  UsbPort? port;
  @override
  void initState() {
    super.initState();
    UsbSerial.usbEventStream?.listen((e) async {
      if(widget.usbdevices.deviceId==e.device?.deviceId&& widget.usbdevices.vid==e.device?.vid&& widget.usbdevices.pid==e.device?.pid){
        if(e.event=="android.hardware.usb.action.USB_DEVICE_ATTACHED"){
          await showDialog(context: context, builder:(c)=>AlertDialog(
            title: const Text("提示"),content:
          const Text("检测到当前已打开设备重新插入"),
            actions: [
              MaterialButton(onPressed:() async {
                Navigator.pop(context);
              },child: const Text("知道了"),),
            ],
          ));
          try{
            port?.close();
            port=await e.device?.create();
            if(port!=null){
              if(await port!.open()){
                await port!.setDTR(true);
                await port!.setRTS(true);
                port!.setPortParameters(9600,UsbPort.DATABITS_8, UsbPort.STOPBITS_1, UsbPort.PARITY_NONE);
                port!.inputStream?.listen((event){
                  print("输入流");
                  print(event);
                });
              }else{
                Fluttertoast.showToast(msg:"串口打开失败");
              }
            }else{
              Fluttertoast.showToast(msg:"获取串口失败");
            }
          }catch(e){
            Fluttertoast.showToast(msg: "错误$e");
          }
        }
        if(e.event=="android.hardware.usb.action.USB_DEVICE_DETACHED"){
          Fluttertoast.showToast(msg: "当前设备已断开，请检查并重新插入");
        }
      }
      setState(() {});
    });
    textController.text="A0 01 01 A2";
    Future.delayed(Duration.zero).then((value) async{
      try{
         port=await widget.usbdevices.create();
        if(port!=null){
          if(await port!.open()){
            await port!.setDTR(true);
            await port!.setRTS(true);
            port!.setPortParameters(9600,UsbPort.DATABITS_8, UsbPort.STOPBITS_1, UsbPort.PARITY_NONE);
            port!.inputStream?.listen((event){
              print("输入流");
              print(event);
            });
          }else{
            Fluttertoast.showToast(msg:"串口打开失败");
          }
        }else{
          Fluttertoast.showToast(msg:"获取串口失败");
        }
      }catch(e){
        Fluttertoast.showToast(msg: "错误$e");
      }
    });
  }
  @override
  void dispose() {
    super.dispose();
    textController.dispose();
  }
  @override
  Widget build(BuildContext context) {
   return Scaffold(body: SafeArea(child: Center(
     child: Padding(
       padding: const EdgeInsets.all(10),
       child: Column(children: [
         const Expanded(child:Text("")),
         Row(children: [
           Expanded(child: TextField(
             controller: textController,
             decoration: const InputDecoration(
                 hintText: "不输入0x，忽略空格"
             ),
           )),ElevatedButton(onPressed:() async {
             var str=textController.text.replaceAll(" ", "");
             List<int> l=[];
             if(str.length.isEven){
               for(var i=0;i<str.length;i=i+2){
                 l.add(int.parse("0X${str[i]}${str[i+1]}"));
               }
               await port?.write(Uint8List.fromList(l));
             }else{
               Fluttertoast.showToast(msg:"请输入偶数位");
             }
           }, child:const Text("send"))
         ],),
       ],),
     ),
   ),),);
  }
}